<template>
  <div class="container">
    <el-dialog :title="curId ? '修改目录' : '新增目录'" :visible="dialogVisible" width="400px" @close="dialogClose" @open="dialogOpen">
      <!-- 表单 -->
      <el-form :model="ruleForm" :rules="rules" ref="dialogRef" label-width="80px" class="demo-ruleForm" size="small">
        <el-form-item v-if="!dirRoute.id" label="所属学科" prop="subjectID">
          <el-select v-model="ruleForm.subjectID" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in subjectList" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input v-model="ruleForm.directoryName" placeholder="请输入学科名称"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogClose">取 消</el-button>
        <el-button type="primary" @click="okBtn">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { add, detail, update } from '@/api/hmmm/directorys'
import { simple } from '@/api/hmmm/subjects'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      default: false
    },
    curId: {
      type: [String, Number],
      required: true
    },
    dirRoute: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      // 弹窗数据
      ruleForm: {
        directoryName: '',
        subjectID: '',
        id: null
      },
      // 弹窗验证
      rules: {
        directoryName: [
          {
            required: true,
            message: '请输入学科名称',
            trigger: 'blur'
          }
        ],
        subjectID: [
          {
            required: true,
            message: '请选择所属学科',
            trigger: 'blur'
          }
        ]
      },
      // 所属学科列表
      subjectList: []
    }
  },
  methods: {
    // 弹窗确认
    okBtn() {
      this.$refs.dialogRef.validate(async (valid) => {
        if (!valid) return
        if (this.ruleForm.creatorID) {
          // 修改
          await update(this.ruleForm)
          this.$message.success('修改目录成功')
        } else {
          await add(this.ruleForm)
          this.$message.success('新增目录成功')
        }
        this.$emit('getDirectorysList')
        this.$emit('dialogClose')
      })
    },
    // 弹窗打开时
    async dialogOpen() {
      if (this.dirRoute.id) {
        this.ruleForm.subjectID = Number(this.dirRoute.id)
      }
      // 获取学科列表
      const res = await simple()
      this.subjectList = res.data
      if (this.curId) {
        // 获取目录详情
        const res = await detail(this.curId)
        this.ruleForm = res.data
      }
    },
    // 关闭弹窗
    dialogClose() {
      this.$emit('dialogClose')
      this.$refs.dialogRef.resetFields()
      this.ruleForm = {
        subjectName: '',
        isFrontDisplay: 1
      }
    }
  }
}
</script>

<style scoped lang='less'></style>

